<template>
  <div v-if="show" class="modal-overlay" @click="$emit('close')">
    <div class="modal-content patient-detail-modal" @click.stop>
      <!-- 头部 -->
      <div class="modal-header">
        <div class="modal-icon">
          <i class="fas fa-user-injured"></i>
        </div>
        <h2 class="modal-title">病人详细信息</h2>
        <button type="button" class="btn-close" @click="$emit('close')">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <!-- 内容区 -->
      <div class="modal-body">
        <!-- 基本信息 -->
        <div class="patient-basic-info">
          <h3 class="section-title">基本信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">姓名：</span>
              <span class="info-value">{{ patient.name || '未填写' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">身份证号：</span>
              <span class="info-value">{{ patient.identity || '未填写' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">手机号码：</span>
              <span class="info-value">{{ patient.phone || '未填写' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">预约时间：</span>
              <span class="info-value">{{ formatTimestamp(patient.createTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 问卷区域 -->
        <div v-if="patient.queryIs === 1" class="patient-questionnaire">
          <div class="questionnaire-badge">病人问卷信息</div>
          <h3 class="section-title">健康问卷</h3>
          <!-- 滚动容器 -->
          <div class="questionnaire-scroll">
            <div class="questionnaire-list">
              <!-- 加载中提示 -->
              <div v-if="isLoading" class="loading-state">
                <i class="fas fa-spinner fa-spin"></i>
                <span>加载问卷答案中...</span>
              </div>
              <!-- 无答案提示 -->
              <div v-else-if="questions.length > 0 && answers.length === 0" class="no-answer-state">
                <p>暂无问卷答案数据</p>
              </div>
              <!-- 循环渲染问答（问题和答案按顺序一一对应） -->
              <div v-else v-for="(q, idx) in questions" :key="idx" class="q-item">
                <p class="q-text">{{ idx + 1 }}. {{ q }}</p>
                <p class="a-text">{{ answers[idx] || '未填写' }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 未填写问卷 -->
        <div v-else class="no-questionnaire">
          <div class="empty-state">
            <i class="fas fa-clipboard-question empty-icon"></i>
            <p>该病人未填写健康问卷</p>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" @click="$emit('close')">
          <i class="fas fa-check"></i> 确定
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import request from '@/utils/request'; // 引入项目的请求工具

const props = defineProps({
  show: Boolean,
  patient: {
    type: Object,
    required: true,
    default: () => ({})
  },
  formatTimestamp: Function,
  questionList: {
    type: Array,
    default: () => []
  }
})

// 问卷问题（从父组件/本地存储取）
const questions = ref([]);
// 问卷答案（从后端接口获取）
const answers = ref([]);
// 加载状态
const isLoading = ref(false);
// 错误状态
const errorMsg = ref('');

// 监听 show 变化：弹窗显示时初始化数据
watch(() => props.show, (newVal) => {
  if (newVal) {
    initData();
  } else {
    // 弹窗关闭时重置数据
    questions.value = [];
    answers.value = [];
  }
}, { immediate: true });

// 初始化问题和答案
const initData = () => {
  // 1. 初始化问题列表
  questions.value = props.questionList.length
    ? props.questionList
    : JSON.parse(localStorage.getItem('questionnaire') || '[]');

  // 2. 如果病人已填写问卷且有 resId，获取答案
  if (props.patient.queryIs === 1 && props.patient.resId) {
    fetchAnswers(props.patient.resId);
  }
};

// 调用后端接口，根据 resId 获取问卷答案
const fetchAnswers = async (resId) => {
  isLoading.value = true;
  try {
    const response = await request({
      url: '/api/perQuery/answers', // 后端接口地址
      method: 'get',
      params: { resId } // 传递 resId 参数给后端
    });

    // 后端返回格式：{ code: 200, msg: "操作成功", data: ["答案1", "答案2", ...] }
    if (response.code === 200) {
      answers.value = response.data || []; // 答案数组与问题数组顺序一一对应
    } else {
      errorMsg.value = response.msg || '获取问卷答案失败';
      console.error('获取问卷答案失败：', response.msg);
    }
  } catch (error) {
    errorMsg.value = '网络异常，获取问卷答案失败';
    console.error('获取问卷答案异常：', error);
  } finally {
    isLoading.value = false;
  }
};

// 计算属性：显示错误提示（优先显示接口错误）
const showError = computed(() => {
  return errorMsg.value && questions.length > 0;
});
</script>

<style scoped>
/* 原有样式保持不变，新增以下样式 */

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 30px 0;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.loading-state .fa-spinner {
  font-size: 18px;
  color: #409eff;
}

/* 无答案状态 */
.no-answer-state {
  text-align: center;
  padding: 30px 0;
  color: #999;
  font-size: 14px;
}

/* 错误状态 */
.error-state {
  text-align: center;
  padding: 30px 0;
  color: #f56c6c;
  font-size: 14px;
}

/* 原有样式保持不变... */
/* 以下是原有样式，确保不缺失 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}
.modal-content {
  width: 500px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  overflow: hidden;
}
.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.modal-icon {
  color: #409eff;
  font-size: 18px;
  margin-right: 8px;
}
.modal-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}
.btn-close {
  border: none;
  background: transparent;
  font-size: 18px;
  color: #999;
  cursor: pointer;
}
.modal-body {
  padding: 20px;
}
.patient-basic-info .section-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}
.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}
.info-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.info-label {
  font-size: 14px;
  color: #666;
  min-width: 60px;
}
.info-value {
  font-size: 14px;
  color: #333;
}
.patient-questionnaire {
  margin-top: 20px;
  position: relative;
}
.questionnaire-badge {
  position: absolute;
  top: -10px;
  right: 0;
  background: #67c23a;
  color: #fff;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}
.patient-questionnaire .section-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}
.questionnaire-scroll {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 8px;
}
.questionnaire-scroll::-webkit-scrollbar {
  width: 6px;
}
.questionnaire-scroll::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 3px;
}
.q-item {
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
}
.q-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}
.q-text {
  font-size: 14px;
  color: #333;
  margin: 0 0 4px 0;
}
.a-text {
  font-size: 14px;
  color: #999;
  margin: 0;
  padding-left: 4px;
}
.no-questionnaire {
  padding: 30px 0;
  text-align: center;
}
.empty-icon {
  font-size: 24px;
  color: #ccc;
  margin-bottom: 8px;
}
.empty-state p {
  font-size: 14px;
  color: #999;
  margin: 0;
}
.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #eee;
  text-align: right;
}
.btn-primary {
  background: #409eff;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}
</style>